package dyyx;

import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.Field.Store;
import org.apache.lucene.document.IntPoint;
import org.apache.lucene.document.NumericDocValuesField;
import org.apache.lucene.document.StoredField;
import org.apache.lucene.document.StringField;
import org.apache.lucene.document.TextField;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;

public class IndexDemo {

	public static void main(String[] args) throws Exception {
		System.out.println("hello,lucene Index," + new Date());

		System.out.println("index dir " + FileUtil.INDEX_DIR);

		Directory indexDir = FSDirectory.open(Paths.get(FileUtil.INDEX_DIR));
		Analyzer analyzer = new StandardAnalyzer();

		IndexWriterConfig iwc = new IndexWriterConfig(analyzer);
		// Creates a new index or overwrites an existing one. 
		iwc.setOpenMode(IndexWriterConfig.OpenMode.CREATE);
		IndexWriter writer = new IndexWriter(indexDir, iwc);

		System.out.println("data file " + FileUtil.DATA_FILE);

		List<String> list = FileUtil.readLinesFromResource(FileUtil.DATA_FILE, null);

		System.out.println("doc num " + list.size());
        int id = 0;
		for (String item : list) {
			id++;
			System.out.println(item);
			Document doc = new Document();
			Field contentField = new TextField("content", item, Store.NO);
			doc.add(contentField);
			
			Field idField = new StringField("id", id+"" ,Store.YES);
			doc.add(idField);
			
			Field lengthField = new NumericDocValuesField("length", item.length());
			doc.add(lengthField);
			
		
			Field lengthField2 = new IntPoint("length2", item.length());
			doc.add(lengthField2);
			
			// StoredField  A field whose value is stored so that IndexSearcher#doc  and IndexReader#document  will return the field and its value.
			Field lengthField3 = new StoredField("length3", item.length());
			doc.add(lengthField3);
						
						
						
			writer.addDocument(doc);
		}

		writer.close();

		System.out.println("\n\n index done,doc count " + list.size() + "," + LocalDateTime.now());

	}
}
